extends CharacterBody2D
class_name Slime

signal die

@export var stats: PandoraEntity
@export var max_splits: int = 2
@onready var body: Node2D = %body
@onready var sprite: AnimatedSprite2D = %sprite
@onready var shadow: AnimatedSprite2D = %shadow
@onready var attack_vfx: AnimatedSprite2D = %attack_vfx
@onready var enemy_health_component: EnemyHealthComponent = %EnemyHealthComponent
@onready var enemy_hit_box_component: EnemyHitBoxComponent = %EnemyHitBoxComponent
@onready var collision_shape_2d: CollisionShape2D = %CollisionShape2D

var slime_stats: PandoraEntity
var split_count: int = 0
var override_stats: Dictionary = {}
var initial_health: float = -1.0
var is_invincible: bool = false  # 无敌状态
var invincible_timer: Timer      # 无敌时间计时器

const SLIME_SCENE: PackedScene = preload("res://scenes/entities/enemy/slime/slime.tscn")
const INVINCIBLE_DURATION: float = 1.0  # 无敌时间1秒

func _ready() -> void:
	if stats != null:
		slime_stats = stats.instantiate()
	enemy_health_component.die.connect(on_die)
	enemy_health_component.on_first_half_hp.connect(_on_first_half_hp)
	add_to_group("boss_slime")
	
	# 设置无敌状态
	_setup_invincibility()
	
	# 应用父代传入的属性覆盖（用于分裂后的子史莱姆）
	if override_stats.size() > 0:
		for k in override_stats.keys():
			var v = override_stats[k]
			if typeof(v) == TYPE_FLOAT or typeof(v) == TYPE_INT:
				slime_stats.set_float(str(k), float(v))
			else:
				# 仅处理数值型覆盖
				pass
	# 如果需要覆盖初始血量（用于分裂后延续父代剩余血量）
	if initial_health >= 0.0:
		await enemy_health_component.ready
		enemy_health_component.health = initial_health
	enemy_hit_box_component.damage = slime_stats.get_float("damage")

	
## 获取速度
func get_safe_velocity() -> Vector2:
	var target_player = Utils.player
	if target_player != null:
		# 检查玩家是否隐身
		var player_is_stealthed = EnemyManager.is_player_stealthed()
		
		# 如果玩家隐身，返回零速度
		if player_is_stealthed:
			return Vector2.ZERO
		
		var next_path_position = target_player.global_position
		var current_agent_position: Vector2 = self.global_position
		var new_velocity: Vector2 = current_agent_position.direction_to(next_path_position) * slime_stats.get_float("speed")
		if new_velocity.x < 0:
			sprite.flip_h = true
			shadow.flip_h = true
		elif new_velocity.x > 0:
			sprite.flip_h = false
			shadow.flip_h = false
		return new_velocity
	else:
		return Vector2.ZERO	

func get_stats():
	return slime_stats

func on_die():
	die.emit()

func _on_first_half_hp() -> void:
	if split_count >= max_splits:
		return
	_split_into_two()

func _split_into_two() -> void:
	# 计算子代属性：体积减半、血量减半、移动速度翻倍、攻击速度与攻速频率翻倍
	var parent_speed := slime_stats.get_float("speed")
	var parent_attack_speed := slime_stats.get_float("attack_speed")
	var parent_attack_delay := slime_stats.get_float("attack_delay")
	var parent_max_health := slime_stats.get_float("max_health")

	var child_speed: float = max(1.0, parent_speed * 2.0)
	var child_attack_speed: float = max(1.0, parent_attack_speed * 2.0)
	var child_attack_delay: float = max(0.05, parent_attack_delay * 0.5) # 攻击更频繁
	var child_max_health: float = max(1.0, parent_max_health * 0.5)

	var parent_node := get_parent()
	if parent_node == null:
		return

	# 计算把父体当前血量均分给两个子体
	var parent_current_hp: float = enemy_health_component.health
	var share_hp: float = max(0.0, parent_current_hp * 0.5)

	for i in 2:
		var child: Slime = SLIME_SCENE.instantiate()
		child.split_count = split_count + 1
		child.max_splits = max_splits
		child.scale = self.scale * 0.5
		child.global_position = self.global_position + Vector2(randf_range(-8.0, 8.0), randf_range(-8.0, 8.0))
		child.override_stats = {
			"speed": child_speed,
			"attack_speed": child_attack_speed,
			"attack_delay": child_attack_delay,
			"max_health": child_max_health,
		}
		# 子体初始血量 = min(子体上限, 均分的父体当前血量)
		child.initial_health = min(child_max_health, share_hp)
		# 使用call_deferred确保子节点在下一帧添加，避免在_ready过程中出现问题
		parent_node.call_deferred("add_child", child)
		
	for child in self.get_children():
		child.call_deferred("queue_free")
	await get_tree().create_timer(INVINCIBLE_DURATION).timeout
	# 原体移除
	queue_free()

## 设置无敌状态
func _setup_invincibility() -> void:
	is_invincible = true
	
	# 创建无敌时间计时器
	invincible_timer = Timer.new()
	invincible_timer.wait_time = INVINCIBLE_DURATION
	invincible_timer.one_shot = true
	invincible_timer.timeout.connect(_on_invincible_timeout)
	add_child(invincible_timer)
	
	# 启动计时器
	invincible_timer.start()
	
	# 可选：添加视觉提示（闪烁效果）
	_start_invincible_visual_effect()

## 无敌时间结束
func _on_invincible_timeout() -> void:
	is_invincible = false
	_stop_invincible_visual_effect()

## 开始无敌视觉效果
func _start_invincible_visual_effect() -> void:
	# 创建闪烁效果
	var tween = create_tween()
	tween.set_loops()
	tween.tween_property(sprite, "modulate:a", 0.5, 0.1)
	tween.tween_property(sprite, "modulate:a", 1.0, 0.1)
	
	# 存储tween引用以便停止
	sprite.set_meta("invincible_tween", tween)

## 停止无敌视觉效果
func _stop_invincible_visual_effect() -> void:
	# 停止闪烁效果
	if sprite.has_meta("invincible_tween"):
		var tween = sprite.get_meta("invincible_tween")
		if tween:
			tween.kill()
		sprite.remove_meta("invincible_tween")
	
	# 恢复正常显示
	sprite.modulate.a = 1.0

## 检查是否无敌
func is_invincible_state() -> bool:
	return is_invincible
